<template>
  <el-dialog
    v-model="visible"
    :title="title"
    :width="autoWidth"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="close"
    append-to-body
    v-bind="$attrs"
  >
    <slot name="content"></slot>
    <template #footer>
      <div class="dialog-footer">
        <el-button v-if="showSubmit" type="primary" :loading="loading" should-add-space @click="submitForm">
          {{ submitValue }}
        </el-button>
        <el-button type="primary" should-add-space @click="close">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
defineOptions({
  name: "Dialog",
  /** 禁用自动继承属性 */
  inheritAttrs: false
});

// 属性
const props = defineProps({
  // 弹窗标题
  title: { type: String, default: "标 题" },
  // 是否展示弹窗
  open: { type: Boolean, default: false },
  // 是否立刻执行初始化方法
  execute: { type: Boolean, default: true },
  // 弹窗宽度
  autoWidth: { type: String, default: "50%" },
  // 是否展示确定按钮
  showSubmit: { type: Boolean, default: true },
  // 设置按钮字符
  submitValue: { type: String, default: "确定" }
});
// 事件
const emits = defineEmits(["submit", "close", "handle-init", "update:open"]);

//外部方法是否完成，默认完成，用来控制是否关闭弹窗
let done = ref(true);
//确认按钮请求中效果
let loading = ref(false);
let visible = computed({
  get() {
    return props.open;
  },
  set(val) {
    emits("update:open", val);
  }
});

/** 监听 */
watch(
  () => props.open,
  (open) => {
    if (open === true && props.execute === true) {
      emits("handle-init");
    }
  }
);
/** 关闭弹窗 */
const close = () => {
  emits("close");
  emits("update:open", false);
};
/** 提交按钮 */
const submitForm = async () => {
  await new Promise((resolve) => {
    loading.value = true;
    /** 注意事项，调用的submit必须有回调方法，否则窗口不会关闭 */
    emits("submit", (res) => {
      done.value = res;
      resolve();
    });
  });
  if (done.value) {
    close();
  }
  loading.value = false;
};
</script>

<style lang="scss" scoped>
.dialog-footer {
  margin-bottom: 10px;
}
</style>
